const { User, Order, PointsTransaction, Product } = require('../../models');

class TestDataHelper {
  constructor() {
    this.createdUsers = [];
    this.createdOrders = [];
    this.createdTransactions = [];
    this.createdProducts = [];
  }

  // 创建测试用户
  async createTestUser(userData = {}) {
    const defaultData = {
      nickname: `测试用户${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      phone: `1${Math.floor(Math.random() * 9000000000 + 1000000000)}`,
      role: 'user',
      points: 100,
      password: 'test123456',
      ...userData
    };

    const user = await User.create(defaultData);
    this.createdUsers.push(user.id);
    return user;
  }

  // 创建管理员用户
  async createTestAdmin(userData = {}) {
    return this.createTestUser({
      role: 'admin',
      nickname: `测试管理员${Date.now()}`,
      ...userData
    });
  }

  // 创建测试商品
  async createTestProduct(productData = {}) {
    const defaultData = {
      name: `测试商品${Date.now()}`,
      description: '这是一个测试商品',
      points_price: 50,
      stock: 100,
      status: 'active',
      category: 'test',
      ...productData
    };

    const product = await Product.create(defaultData);
    this.createdProducts.push(product.id);
    return product;
  }

  // 创建测试订单
  async createTestOrder(userId, orderData = {}) {
    const defaultData = {
      userId,
      orderNumber: `TEST${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      status: 'pending',
      totalPoints: 50,
      pointsUsed: 50,
      type: 'offline',
      items: JSON.stringify([{
        productId: 1,
        productName: '测试商品',
        quantity: 1,
        pointsUsed: 50
      }]),
      ...orderData
    };

    const order = await Order.create(defaultData);
    this.createdOrders.push(order.id);
    return order;
  }

  // 创建测试积分交易
  async createTestTransaction(userId, transactionData = {}) {
    const user = await User.findByPk(userId);
    const balanceBefore = user ? user.points : 0;

    const defaultData = {
      userId,
      type: 'earn',
      amount: 10,
      source: 'test',
      description: '测试积分交易',
      balanceBefore,
      balanceAfter: balanceBefore + 10,
      ...transactionData
    };

    const transaction = await PointsTransaction.create(defaultData);
    this.createdTransactions.push(transaction.id);
    return transaction;
  }

  // 创建多个测试用户
  async createMultipleTestUsers(count = 5, userData = {}) {
    const users = [];
    for (let i = 0; i < count; i++) {
      const user = await this.createTestUser({
        nickname: `测试用户${i + 1}_${Date.now()}`,
        ...userData
      });
      users.push(user);
    }
    return users;
  }

  // 创建完整的测试场景数据
  async createTestScenario() {
    // 创建用户
    const user = await this.createTestUser();
    const admin = await this.createTestAdmin();

    // 创建商品
    const product = await this.createTestProduct();

    // 创建订单
    const order = await this.createTestOrder(user.id);

    // 创建积分交易
    const transaction = await this.createTestTransaction(user.id);

    return {
      user,
      admin,
      product,
      order,
      transaction
    };
  }

  // 清理所有创建的测试数据
  async cleanup() {
    try {
      // 删除积分交易记录
      if (this.createdTransactions.length > 0) {
        await PointsTransaction.destroy({
          where: { id: this.createdTransactions }
        });
      }

      // 删除订单
      if (this.createdOrders.length > 0) {
        await Order.destroy({
          where: { id: this.createdOrders }
        });
      }

      // 删除商品
      if (this.createdProducts.length > 0) {
        await Product.destroy({
          where: { id: this.createdProducts }
        });
      }

      // 删除用户
      if (this.createdUsers.length > 0) {
        await User.destroy({
          where: { id: this.createdUsers }
        });
      }

      // 重置数组
      this.createdUsers = [];
      this.createdOrders = [];
      this.createdTransactions = [];
      this.createdProducts = [];

      console.log('测试数据清理完成');
    } catch (error) {
      console.error('清理测试数据失败:', error);
    }
  }
}

module.exports = TestDataHelper;